package org.wltea.dichotload;

import org.wltea.analyzer.cfg.DefaultConfig;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Date;
import java.util.Properties;
import java.util.Timer;

/**
 * 一期：类名、contextInitialized，getZKAddress方法都不能修改
 * 
 * @author huhailiang937
 * @date 2017年4月25日下午1:36:47
 * @since 1.0.0
 */
public class DicLoadScheduler implements ServletContextListener {


    // 一期基于IK5.3版本做的一个粗略版本
    public static String zkHost;

    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();

        Timer timer = new Timer();

        DicLoadTask task = new DicLoadTask(servletContext);

        int interval = DefaultConfig.getInstance().getDictReloadInterval().intValue();

        if (interval == 0)
            return;

        Calendar calendar = Calendar.getInstance();

        calendar.add(Calendar.MINUTE, interval);
        Date startTime = calendar.getTime();

        timer.scheduleAtFixedRate(task, startTime, 60000 * interval);

        servletContext.setAttribute("timer", timer);
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
    }

    public String getZKAddress() {
        if (null != zkHost) {
            return zkHost;
        }

        Properties props = new Properties();

        InputStream input = getClass().getClassLoader().getResourceAsStream("const.properties");
        if (input != null) {
            try {
                props.load(input);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return props.getProperty("ZK_Address");
    }


}